package com.zhiyume.service;

import com.zhiyume.dao.api.TUserMapper;
import com.zhiyume.dao.entity.TUser;
import com.zhiyume.dao.entity.TUserCriteria;
import com.zhiyume.dto.RegisterReqDTO;
import com.zhiyume.dto.RegisterResDTO;
import com.zhiyume.service.common.ConstantEnum;
import com.zhiyume.service.common.UserEnum;
import com.zhiyume.service.util.DateUtil;
import com.zhiyume.service.util.EncryptUtil;
import com.zhiyume.service.util.GenerateKeyUtil;
import com.zhiyume.util.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class RegisterService {
    @Autowired
    private TUserMapper tUserMapper;
    @Autowired
    private RedisClient redisClient;

    public RegisterResDTO register(RegisterReqDTO reqDTO){
        TUserCriteria example = new TUserCriteria();
        TUserCriteria.Criteria c  = example.createCriteria();
        c.andStatusNotEqualTo(UserEnum.USER_STATUS_CACELED.getValue());
        c.andUserNameEqualTo(reqDTO.getUserName());
        List<TUser> list = tUserMapper.selectByExample(example);
        RegisterResDTO resDTO = new RegisterResDTO();
        if(null != list && list.size() >0 ) {
            return resDTO;
        }
        long id = GenerateKeyUtil.generationPK();
        TUser tUser = new TUser();
        tUser.setId(id);
        tUser.setUserName(reqDTO.getUserName());
        tUser.setNickName(reqDTO.getUserName());
        tUser.setPassword(EncryptUtil.SHA256(reqDTO.getPassword()));
        tUser.setCreateTime(DateUtil.getNow());
        tUserMapper.insertSelective(tUser);
        resDTO.setuId(id);
        String token = UUID.randomUUID().toString().toLowerCase()+new Date().getTime();
        try {
            redisClient.setx(ConstantEnum.CONSTANT_TOKEN_PRE.getErrType() + token, String.valueOf(id), UserEnum.USER_TOKEN_TIME.getValue());
        }catch (Exception e){
            return resDTO;
        }
        resDTO.setToken(token);
        resDTO.setuId(id);

        return resDTO;
    }
}
